// 云函数入口文件
const cloud = require('wx-server-sdk')
const mysql = require('mysql2/promise')

cloud.init({
  env: 'uniapp-8g0lywngd57d5c18'
})

// MySQL连接配置
const config = {
  host: 'sh-cynosdbmysql-grp-b4b8nkho.sql.tencentcdb.com',
  port: 25932,
  database: 'custom_order_management',
  user: 'root',
  password: 'jQ6w2uwY',
  // 添加连接选项
  connectTimeout: 10000, // 连接超时时间10秒
  connectionLimit: 10,   // 连接池限制
  waitForConnections: true,
  queueLimit: 0
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const type = event.type || 'user' // 登录类型：user或merchant
  
  console.log('获取到的openid:', openid)
  console.log('登录类型:', type)

  let connection
  try {
    // 创建数据库连接
    connection = await mysql.createConnection(config)

    if (type === 'merchant') {
      console.log('执行商家登录逻辑')
      
      // 直接查询商家用户表
      const [merchants] = await connection.execute(
        'SELECT * FROM merchant_user WHERE openid = ?',
        [openid]
      )
      
      console.log('商家查询结果:', JSON.stringify(merchants))
      
      if (merchants.length === 0) {
        console.log('商家不存在，返回新用户标识')
        return {
          isNewUser: true
        }
      }

      const merchant = merchants[0]
      console.log('找到商家:', JSON.stringify(merchant))

      // 返回商家信息
      return {
        isNewUser: false,
        userId: merchant.user_id,
        merchantInfo: {
          shopName: merchant.merchant_name,
          taobaoId: merchant.taobao_id
        }
      }
    } else {
      // 普通用户登录逻辑
      const [users] = await connection.execute(
        'SELECT m.*, mg.manager_id as is_manager FROM member m LEFT JOIN manager mg ON m.user_id = mg.user_id WHERE m.openid = ?',
        [openid]
      )
      
      console.log('查询结果:', JSON.stringify(users))

      if (users.length === 0) {
        console.log('用户不存在，返回新用户标识')
        return {
          isNewUser: true
        }
      }

      const user = users[0]
      console.log('找到用户:', JSON.stringify(user))
      
      // 如果用户是管理员，获取管理员信息
      let managerInfo = null
      if (user.is_manager) {
        console.log('用户是管理员���查询管理员信息')
        const [managers] = await connection.execute(
          'SELECT * FROM manager WHERE user_id = ?',
          [user.user_id]
        )
        console.log('管理员查询结果:', JSON.stringify(managers))
        if (managers.length > 0) {
          managerInfo = managers[0]
        }
      }

      // 返回用户信息
      return {
        isNewUser: false,
        userId: user.user_id,
        studentId: user.student_id,
        managerId: managerInfo ? managerInfo.manager_id : null,
        userName: user.user_name,
        managerInfo: managerInfo ? {
          phone: managerInfo.contact_info
        } : null
      }
    }

  } catch (error) {
    console.error('登录失败:', error)
    return {
      error: error.message
    }
  } finally {
    if (connection) {
      await connection.end()
    }
  }
} 